package com.loan.market.util

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.LifecycleCoroutineScope
import androidx.lifecycle.lifecycleScope
import com.orhanobut.logger.Logger
import kotlinx.coroutines.CoroutineExceptionHandler
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

fun AppCompatActivity.timer(time: Int = 60, block: (time: Int, finish: Boolean) -> Unit) {
    lifecycleScope.launch {
        for (i in time downTo -1) {
            block(i, i < 0)
            delay(1000)
        }
    }
}

fun AppCompatActivity.http(
    onFail: Throwable.() -> Unit = {},
    onFinish: () -> Unit = {},
    showError: () -> Boolean = { true },
    onLoading: suspend CoroutineScope.() -> Unit
) {
    lifecycleScope.http(onFail, onFinish, showError, onLoading)
}

fun Fragment.http(
    showError: () -> Boolean = { true },
    onFail: Throwable.() -> Unit = {},
    onFinish: () -> Unit = {},
    onLoading: suspend CoroutineScope.() -> Unit
) {
    viewLifecycleOwner.lifecycleScope.http(onFail, onFinish, showError, onLoading)
}

fun LifecycleCoroutineScope.http(
    onFail: Throwable.() -> Unit = {},
    onFinish: () -> Unit = {},
    showError: () -> Boolean = { true },
    onLoading: suspend CoroutineScope.() -> Unit
) {
    launch(CoroutineExceptionHandler { _, throwable ->
        Logger.e(throwable.toString())
        onFail(throwable)
        onFinish()
        if (showError()) {
            showToast(throwable.message)
        }
    }) {
        onLoading()
        onFinish()
    }
}

